// "attitudes_count": 0, // 点赞数
//  "comments_count": 0, // 评论数
//  "reposts_count": 0, // 转发数
// "reads_count": 0, // 阅读数

// var data = ["1,2,3\n","4,5,6"] // 每一行数据为一个字符串，字符串用“,”隔开，并且在每一行加上换行符
// var blob = new Blob(data, {type:"text/csv,charset=UTF-8"})
// var csvUrl = URL.createObjectURL(blob)
// var aEle = document.createElement("a")
// aEle.download = "data.csv" //文件名随意
// aEle.href = csvUrl
// aEle.click()

var sunac_data = {
  "data": {},
  "topic": {},
  "feed_date": []
}
// var patt = new RegExp('#.{1,15}.#', 'g')
var patt = new RegExp('#(.*?)#', 'g')
document.onreadystatechange = async function () {
  if (document.readyState == 'complete') {
    // 插入动画样式
    setCSSStyle()
    // 插入数据区域
    floatWrap()
    let weibo_id
    let weibo_uid
    getWeiboConfig().then( async function(val){
      weibo_id = val['page_id']
      weibo_uid = val['uid']
      let page = 1
      //await getFeedData(page,weibo_id,weibo_uid)
      while (page <= 12) {
        await getFeedData(page,weibo_id,weibo_uid)
        page +=1
      }
      console.log(sunac_data)
      //innerData(sunac_data)
      // innerHTMLToPage(sunac_data)
      let dataBtnElement = document.getElementById('data-show-btn')
      let dataDownloadBtnElement = document.getElementById('data-download-btn')
      let dataTipsElement = document.getElementById('data-tips')
      dataBtnElement.style.backgroundColor = '#67C23A'
      dataDownloadBtnElement.style.backgroundColor = '#E6A23C'
      dataBtnElement.removeAttribute('disabled')
      dataDownloadBtnElement.removeAttribute('disabled')
      dataTipsElement.innerText = '数据已拉取~'
    })
  }
    

}

function floatWrap(){
  /**
   * 创建数据显示区域，并添加相应的css动画
   * 
   */
  // const APPElement = document.getElementById('app')
  const APPElement = document.body
  const floatWrap = document.createElement('div')
  floatWrap.setAttribute('id', 'float-wrap')
  floatWrap.style.position = 'fixed'
  floatWrap.style.top = '100px'
  floatWrap.style.left = '-300px'  
  floatWrap.style.width = '350px'
  floatWrap.style.height = '800px'
  floatWrap.style.backgroundColor = 'rgba(0,0,0,.9)'
  floatWrap.style.zIndex = '1000'
  floatWrap.style.overflowY = 'scroll'
  // floatWrap.style.userSelect = 'none'
  floatWrap.style.animationFillMode = 'forwards'
  floatWrap.ondblclick = function(){
    if(floatWrap.style.left == '-300px'){
      floatWrap.style.animation = 'floatWrapKeyFramesRight 1.0s'
      floatWrap.addEventListener('webkitAnimationEnd', function () {
        floatWrap.style.left = '0px'
      })
    } else {
      floatWrap.style.animation = 'floatWrapKeyFramesLeft 1.0s'
      floatWrap.addEventListener('webkitAnimationEnd', function () {
        floatWrap.style.left = '-300px'
      })
    }
  }
  APPElement.appendChild(floatWrap)
  const dataTitle = '<div style="margin-top:20px;text-align:center;font-size:16px;color:white;font-weight:bold;">微博数据<button type="button" id="data-show-btn" style="width:40px;height:25px;margin-left:10px;background-color:#909399;color:white;border:none;border-radius:5px;" disabled="disabled">查看</button><button type="button" id="data-download-btn" style="width:40px;height:25px;margin-left:10px;background-color:#909399;color:white;border:none;border-radius:5px;" disabled="disabled">下载</button><span id="data-tips" style="display:inline-block;margin-left:10px;font-size:9px;">数据正在拉取~</span></div>'
  const dataArea = '<div id="data-area"></div>'
  floatWrap.innerHTML = dataTitle + dataArea
  document.getElementById('data-show-btn').onclick = function(){
    handleGetData(sunac_data)
  }
  document.getElementById('data-download-btn').onclick = function(){
    let feed_data = sunac_data['feed_date']
    let filename = ((new Date).getTime()).toString() + '.xlsx'
    saveXLSX(filename,feed_data)
    alert('数据已下载，数据文件名为' + filename)
  }

}

function setCSSStyle(){
  /**
   * 写入动画样式
   */
    const head = document.getElementsByTagName('head')[0]
    const styleElement = `
      <style type="text/css">
        #float-wrap::-webkit-scrollbar {
          display: none;
        }
        @keyframes floatWrapKeyFramesRight {
          from {
            left: -300px;
          }
          to {
            left: 0px;
          }
        }
        
        @keyframes floatWrapKeyFramesLeft {
          from {
            left: 0px;
          }
          to {
            left: -300px;
          }
        }
      </style>
    `
    head.innerHTML = head.innerHTML + styleElement
}

function handleGetData(data){
  innerData(data)
}

function getWeiboConfig() {
  return new Promise(resolve => {
    injectCustomJs('js/inject_script.js');
    window.addEventListener('message', function (e) {
      resolve(e.data['weibo_config'] || '未获取到');
    }, false);
  });
}

async function getFeedData(page,weibo_id,weibo_uid){
  const res = await fetch(
    "https://weibo.com/ajax/statuses/mymblog?uid=" + weibo_uid + "&rank=1&page=" + page,
    {
      "headers": {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "sec-ch-ua": '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
        "sec-ch-ua-mobile": "?0",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
      },
      "referrer": "https://weibo.com/p/" + weibo_id,
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "include"
    }
  )
  const result = await res.json()
  if(result.hasOwnProperty('data') && result['data'].hasOwnProperty('list')){
    let feed_list = result['data']['list']
    feed_list.forEach((item) => {
      if(item.hasOwnProperty('visible') && item['visible'].hasOwnProperty('type') && item['visible']['type'] == 0 ){ //visible.type = 0 表示公开 1 表示仅自己可见
        let d = new Date(item['created_at'])
        feed_date = d.getFullYear() + '-' + (d.getMonth() + 1)
        if(!sunac_data['data'].hasOwnProperty(feed_date)){
          sunac_data['data'][feed_date] = {
            "attitudes_count": 0, // 点赞数
            "comments_count": 0, // 评论数
            "reposts_count": 0, // 转发数
            "reads_count": 0, // 阅读数
            "feed_count": 0, // 微博数量,
            "retweet_count": 0, // 转发微博数量
            "topic": {}
          }
        }
        sunac_data['data'][feed_date]['attitudes_count'] += item['attitudes_count']
        sunac_data['data'][feed_date]['comments_count'] += item['comments_count']
        sunac_data['data'][feed_date]['reposts_count'] += item['reposts_count']
        sunac_data['data'][feed_date]['reads_count'] += item['reads_count']
        if(item.hasOwnProperty('retweeted_status')){
          sunac_data['data'][feed_date]['retweet_count'] += 1
        } else {
          sunac_data['data'][feed_date]['feed_count'] += 1
        }
        weibo_text_raw = item['text']
        let match_topic_data = weibo_text_raw.match(patt)
        if(match_topic_data != null){
          let topic_data = Array.from(new Set(match_topic_data)) // 去重 去除同一条微博中重复的话题
          for (const value of topic_data) {
            if (!sunac_data['topic'].hasOwnProperty(value)) {
              sunac_data['topic'][value] = []
            }
            sunac_data['topic'][value].push(
              {
                'attitudes_count': item['attitudes_count'],
                'comments_count': item['comments_count'],
                'reposts_count': item['reposts_count'],
                'reads_count': item['reads_count'],
                'feed_date': feed_date,
                'text': weibo_text_raw
              }
            )
            if(!sunac_data['data'][feed_date]['topic'].hasOwnProperty(value)){
              sunac_data['data'][feed_date]['topic'][value] = []
            }
            sunac_data['data'][feed_date]['topic'][value].push(
              {
                'attitudes_count': item['attitudes_count'],
                'comments_count': item['comments_count'],
                'reposts_count': item['reposts_count'],
                'reads_count': item['reads_count'],
                'feed_date': feed_date,
                'text': weibo_text_raw
              }
            )
          }
        }

        // 记录微博信息 feed_data
        let feed_push_date =  d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
        sunac_data['feed_date'].push([weibo_text_raw,item['attitudes_count'],item['comments_count'],item['reposts_count'],item['reads_count'],feed_push_date])
      }
    })
  }
  // return result
}
// function innerHTMLToPage(data){
//   const parentNode = document.getElementsByClassName('WB_frame_b')[0]
//   if(parentNode != undefined){
//     let element = '<div id="Pl_Core_T8CustomTriColumn__3" anchor="-50"><div class="WB_cardwrap S_bg2"><div class="PCD_counter"><div class="WB_innerwrap"><table class="tb_counter" cellpadding="0" cellspacing="0"><tbody>'
//     for (const key in data) {
//       element += '<tr><td class="S_line1"><strong class="W_f16" style="font-size:12px;">' + key + '</strong><span class="S_txt2" style="display:inline-block;font-size:12px;margin-bottom:10px">日期</span></td><td class="S_line1"><strong class="W_f16" style="font-size:12px;">' + data[key]['attitudes_count'] + '</strong><span class="S_txt2" style="display:inline-block;font-size:12px;margin-bottom:10px">点赞数</span></td><td class="S_line1"><strong class="W_f16" style="font-size:12px;">' + data[key]['comments_count'] + '</strong><span class="S_txt2" style="display:inline-block;font-size:12px;margin-bottom:10px">评论数</span></td><td class="S_line1"><strong class="W_f16" style="font-size:12px;">' + data[key]['reposts_count'] + '</strong><span class="S_txt2" style="display:inline-block;font-size:12px;margin-bottom:10px">转发数</span></td><td class="S_line1"><strong class="W_f16" style="font-size:12px;">' + data[key]['reads_count'] + '</strong><span class="S_txt2" style="display:inline-block;font-size:12px;margin-bottom:10px">阅读数</span></td></tr>'
//     }
//     element += '</tbody></table></div></div></div></div>'
//     oldElement = parentNode.innerHTML
//     parentNode.innerHTML = element + oldElement
//   }
  
// }
function innerData(data){
  const parentNode = document.getElementById('data-area')
  // const childInnerHTML = parentNode.innerHTML
  let dataElement = ''
  if(data.hasOwnProperty('data')){
    const feed_data = data['data']
    for (const key in feed_data) {
      let tmpStartElement = '<div style="padding-left:20px;padding-bottom:20px;color:white;border-bottom: 1px white solid;">'
      let tmpElement = '<div style="margin-top:20px;text-align:center;font-size:15px;">'+ key.replace('-','年') +'月 基本数据统计</div>'
      let basicDataElement = '<div style="margin-top: 10px;margin-bottom:20px;font-size: 14px;"><div style="display:inline-block;width:130px;margin-bottom:5px;">原创微博：' + feed_data[key]['feed_count']+ '</div><div style="display:inline-block;width:130px;margin-bottom:5px;">转发微博：' + feed_data[key]['retweet_count'] + '</div><div style="display:inline-block;width:130px;margin-bottom:5px;">总阅读数：' + feed_data[key]['reads_count'] + '</div><div style="display:inline-block;width:130px;margin-bottom:5px;">总点赞数：' + feed_data[key]['attitudes_count'] + '</div><div style="display:inline-block;width:130px;margin-bottom:5px;">总评论数：' + feed_data[key]['comments_count'] + '</div><div style="display:inline-block;width:130px;margin-bottom:5px;">总转发数：' + feed_data[key]['reposts_count'] + '</div></div>'
      const topics = feed_data[key]['topic']
      let tmpTopicElement = ''
      if(Object.keys(topics).length > 0){
        for (const k in topics) {
          tmpTopicElement += '<div style="margin-bottom:10px;">包含话题 ' + k + ' 的微博有 <span style="font-size:14px;font-weight: bold;">' + topics[k].length + ' </span>条</div>'
        }
      }
      let tmpEndElement = '</div>'

      dataElement += tmpStartElement + tmpElement + basicDataElement + tmpTopicElement + tmpEndElement

    }

  }
  parentNode.innerHTML = dataElement
  
}

function saveXLSX(filename, data){
  /**
   * data = [[1,2,3],[1,2,3],[1,2,3]]
   */
  const ws_name = "SheetJS"
  const sheet_title = ['微博','点赞数','评论数','转发数','阅读数','发布时间']
  let sheet_data = data
  sheet_data.unshift(sheet_title)
  //data = data.unshif(sheet_title)
  const wb = XLSX.utils.book_new()
  ws = XLSX.utils.aoa_to_sheet(sheet_data)
  XLSX.utils.book_append_sheet(wb, ws, ws_name)
  XLSX.writeFile(wb, filename)
  console.log('文件已保存~')
}



//向页面注入inject_script
function injectCustomJs(jsPath) {
  jsPath = jsPath || 'js/inject_script.js';
  var temp = document.createElement('script');
  temp.setAttribute('type', 'text/javascript');
  temp.src = chrome.extension.getURL(jsPath);
  temp.onload = function () {
    this.parentNode.removeChild(this);
  };
  document.head.appendChild(temp);
}